//
//  MMUtils.m
//  MemeMaker
//
//  Created by Phan Quang Ha on 7/9/13.
//  Copyright (c) 2013 soyo. All rights reserved.
//

#import "MMUtils.h"
#import "MMWaitingViewController.h"
#import "MMConstants.h"
static MMWaitingViewController *w = nil;

@implementation MMUtils


+(id)loadView:(Class)class FromNib:(NSString*)nibName {
	NSArray* nibViews =  [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil];
	for( id obj in nibViews ) {
		if( [obj isMemberOfClass:class] ) {
			return obj;
		}
	}
//	for( id obj in nibViews ) {
//		if( [obj isKindOfClass:class] ) {
//			return obj;
//		}
//	}
	return nil;
}

+ (void)hideKeyboard:(UIView *)topView {
    for (UIView *v in [topView subviews]) {
        if ([v isKindOfClass:[UITextView class]] || [v isKindOfClass:[UITextField class]] ) {
            [v resignFirstResponder];
        }
        else {
            [self hideKeyboard:v];
        }
    }
}

+ (void)hideKeyboard:(UIView *)topView completion:(void (^)(BOOL finished))completion {
    int i = 0;
    for (UIView *v in [topView subviews]) {
        ++i;
        if ([v isKindOfClass:[UITextView class]] || [v isKindOfClass:[UITextField class]] ) {
            [v resignFirstResponder];
        }
        else {
            [self hideKeyboard:v];
        }
        if (i==[[topView subviews] count]) {
            completion(YES);
        }
    }
}

+ (UIColor *)getColorFromImage:(UIImage *)img atX:(CGFloat)x andY:(CGFloat)y
{
    CGImageRef imageRef = [img CGImage];
    NSUInteger width = CGImageGetWidth(imageRef);
    NSUInteger height = CGImageGetHeight(imageRef);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));
    NSUInteger bytesPerPixel = 4;
    NSUInteger bytesPerRow = bytesPerPixel * width;
    NSUInteger bitsPerComponent = 8;
    CGContextRef context = CGBitmapContextCreate(rawData, width, height,
                                                 bitsPerComponent, bytesPerRow, colorSpace,
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);
    
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
    CGContextRelease(context);
    
    // Now your rawData contains the image data in the RGBA8888 pixel format.
    int byteIndex = (bytesPerRow * y) + x * bytesPerPixel;
    if (rawData) {
        CGFloat red = (rawData[byteIndex] * 1.0) / 255.0f;
        CGFloat green = (rawData[byteIndex + 1] * 1.0) / 255.0f;
        CGFloat blue = (rawData[byteIndex + 2] * 1.0) / 255.0f;
        CGFloat opacity = (rawData[byteIndex +3] *1.0) / 255.0f;
        free(rawData);
        
        return [UIColor colorWithRed:red green:green blue:blue alpha:opacity];
    }else{
        return nil;
    }
}

+ (NSString *)trimString:(NSString*)string {
    NSCharacterSet *charsToTrim = [NSCharacterSet characterSetWithCharactersInString:@" \n"];
    return [string stringByTrimmingCharactersInSet:charsToTrim];
}

+ (BOOL)isIPhone5 {
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    if ([UIScreen mainScreen].scale == 2.f && screenHeight == 568.0f) {
        return YES;
    }
    return NO;
}

+ (void)showAlertView:(NSString *)title andMessage:(NSString *)message {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                    message:message
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
}

+ (CGSize)sizeWindowScreen {
    return CGSizeMake([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 20.0);
}

+ (NSString *)fileNamePath:(NSString*)filename {
    //Get path with file name
    NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [arrayPaths objectAtIndex:0];
    NSString *returnFileName = [path stringByAppendingPathComponent:filename];
    return returnFileName;
}

#pragma mark - Image
+ (UIImage *)newImageFromResource:(NSString *)filename {
    NSString *imageFile = [[NSString alloc] initWithFormat:@"%@/%@",[[NSBundle mainBundle] resourcePath], filename];
    UIImage *image = nil;
    image = [[UIImage alloc] initWithContentsOfFile:imageFile];
    return image;
}

#pragma mark - waiting view function
+ (void) showWatingView {
    [MMUtils showWatingViewWithMessage:@""];
}

+ (void) showWatingViewWithMessage:(NSString *)message {
    if (!w) {
        w = [[MMWaitingViewController alloc] initWithNibName:@"MMWaitingViewController" bundle:nil];
    }
    
    if (w.view.superview) {
        [w startWithMessage:message];
        return;
    }
    w.view.alpha = 1.0f;
    [w.view setFrame:CGRectMake(0, 0, [MMUtils getMainView].frame.size.width, [MMUtils getMainView].frame.size.height)];
    [[MMUtils getMainView] addSubview:w.view];
    CGSize startSize = CGSizeMake(300, 300);
    w.cornerRoundedView.frame = CGRectMake((w.view.frame.size.width - startSize.width)/2,
                                           (w.view.frame.size.height - startSize.height)/2,
                                           startSize.width,
                                           startSize.height);
    [UIView beginAnimations:@"View Flip" context:nil];
    [UIView setAnimationDuration:0.3f];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    
    CGSize  targetSize = CGSizeMake(150, 150);
    w.cornerRoundedView.frame = CGRectMake((w.view.frame.size.width - targetSize.width)/2,
                                           (w.view.frame.size.height - targetSize.height)/2,
                                           targetSize.width,
                                           targetSize.height);
    
    [UIView commitAnimations];
    
    [w startWithMessage:message];
}

+ (void) hideWatingView {
    if (!w) {
        return;
    }
    [w disappear];
}

+ (void) hideWatingViewWithMessage:(NSString *)message {
    if (!w) {
        return;
    }
    [w stop];
    [self waitingViewMessageIs:message];
    [NSTimer scheduledTimerWithTimeInterval:3.0f target:w selector:@selector(disappear) userInfo:nil repeats:NO];
}

+ (UIView *) getMainView {
    return [kMMAppDelegate window];
}

+ (void)waitingViewMessageIs:(NSString*)message {
    if (!w) {
        return;
    }
    w.message.text = message;
}

+ (BOOL)checkFirstLaunch
{
    static NSString* const hasRunAppOnceKey = @"hasRunAppOnceKey";
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults boolForKey:hasRunAppOnceKey] == NO)
    {
        [defaults setBool:YES forKey:hasRunAppOnceKey];
        return YES;
    }else{
        return NO;
    }
}

@end
